package com.zbkj.crmeb.payment.service.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONArray;
import com.taobao.pac.sdk.cp.dataobject.request.MODUAN_ORDER_CREATE.request;
import com.utils.lianlianpay.dto.refund.RefundMethod;
import com.utils.lianlianpay.service.NotifyService;
import com.zbkj.crmeb.chant.model.ChannelMerchantPurchase;
import com.zbkj.crmeb.chant.service.ChannelMerchantPurchaseService;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.constants.Constants;
import com.constants.WeChatConstants;
import com.crmeb.core.exception.CrmebException;
import com.factory.CommonFactory;
import com.huifu.adapay.core.AdapayCore;
import com.huifu.adapay.core.util.AdapaySign;
import com.utils.CrmebUtil;
import com.utils.WxPayUtil;
import com.utils.XmlUtil;
import com.utils.adapay.degree.XMLSecurityProcess;
import com.zbkj.crmeb.chant.model.ChannelMerchantAccount;
import com.zbkj.crmeb.chant.service.IChannelMerchantAccountService;
import com.zbkj.crmeb.chant.service.IChannelMerchantService;
import com.zbkj.crmeb.enums.AccountFlowTypeEnum;
import com.zbkj.crmeb.finance.model.UserRecharge;
import com.zbkj.crmeb.finance.service.UserRechargeService;
import com.zbkj.crmeb.front.request.OrderInfoRequest;
import com.zbkj.crmeb.front.request.OrderPayRequest;
import com.zbkj.crmeb.front.request.PayeeInfoRequest;
import com.zbkj.crmeb.front.request.PayerInfoRequest;
import com.zbkj.crmeb.front.response.CustomsPushPayResponse;
import com.zbkj.crmeb.front.response.LianlianPayResponse;
import com.zbkj.crmeb.front.service.OrderService;
import com.zbkj.crmeb.merchant.api.service.MerOrderService;
import com.zbkj.crmeb.payment.service.CallbackService;
import com.zbkj.crmeb.payment.service.OrderPayService;
import com.zbkj.crmeb.payment.service.RechargePayService;
import com.zbkj.crmeb.payment.service.RefundPayService;
import com.zbkj.crmeb.payment.vo.hkwechat.HkPayAttachVo;
import com.zbkj.crmeb.payment.vo.hkwechat.HkPayCallbackVo;
import com.zbkj.crmeb.payment.vo.wechat.AttachVo;
import com.zbkj.crmeb.payment.vo.wechat.CallbackVo;
import com.zbkj.crmeb.store.model.StoreOrder;
import com.zbkj.crmeb.store.model.StoreOrderCustoms;
import com.zbkj.crmeb.store.service.AccountFlowService;
import com.zbkj.crmeb.store.service.StoreOrderCustomsService;
import com.zbkj.crmeb.store.service.StoreOrderService;
import com.zbkj.crmeb.system.model.SystemConfig;
import com.zbkj.crmeb.system.service.SystemAdminService;
import com.zbkj.crmeb.system.service.SystemConfigService;
import com.zbkj.crmeb.user.model.UserMemberRecord;
import com.zbkj.crmeb.user.model.UserToken;
import com.zbkj.crmeb.user.service.UserMemberRecordService;
import com.zbkj.crmeb.user.service.UserTokenService;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;


/**
 * <p>
 * 支付类
 * </p>
 *
 * @author Mr.Zhang
 * @since 2020-04-10
 */
@Slf4j
@EqualsAndHashCode()
@Data
@Service
@Transactional
public class CallbackServiceImpl implements CallbackService {
    private static final Logger logger = LoggerFactory.getLogger(CallbackServiceImpl.class);
    @Autowired
    private RechargePayService rechargePayService;
    @Lazy
    @Autowired
    private OrderPayService orderPayService;
    @Autowired
    private MerOrderService merOrderService;
    @Autowired
    private UserTokenService userTokenService;
    @Autowired
    private StoreOrderService storeOrderService;
    @Autowired
    private RefundPayService refundPayService;
    @Autowired
    private CommonFactory commonFactory;
    @Autowired
    private UserRechargeService userRechargeService;
    @Autowired
    private IChannelMerchantService channelMerchantService;
    @Autowired
    private IChannelMerchantAccountService channelMerchantAccountService;
    @Autowired
    private AccountFlowService accountFlowService;
    @Autowired
    private SystemAdminService systemAdminService;
    @Autowired
    private SystemConfigService systemConfigService;
    @Autowired
    private UserMemberRecordService userMemberRecordService;
    @Autowired
    private StoreOrderCustomsService storeOrderCustomsService;
    @Autowired
    private ChannelMerchantPurchaseService channelMerchantPurchaseService;
    @Autowired
    private NotifyService notifyService;


    @Value("${orange.secret}")
    private String secret;
	private static final String SIGNATUREPARAMS = "merchantAcctId,terminalId,version,payType,bankId,"
			+ "orderId,orderTime,orderCurrency,orderAmount,dealId,bankDealId,dealTime,"
			+ "ext1,ext2,payResult,errCode";

    /**
     * 微信支付回调
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public Boolean weChat(String request) {
        logger.info("--------------- 微信支付回调原始参数: {} ---------------", request);
        try{
            if(null == request){
                return false;
            }

            HashMap<String, Object> map = XmlUtil.xmlToMap(request);
            if(null == map){
                throw new CrmebException("微信下单失败！");
            }
            //解析xml
            CallbackVo callbackVo = CrmebUtil.mapToObj(map, CallbackVo.class);
            AttachVo attachVo = JSONObject.toJavaObject(JSONObject.parseObject(callbackVo.getAttach()), AttachVo.class);

            logger.info("支付回调成功,callbackVo对象:{}",callbackVo);

            if (!attachVo.getType().equals(Constants.SERVICE_PAY_TYPE_PRODUCT) && !attachVo.getType().equals(Constants.SERVICE_PAY_TYPE_MEMBER)) {
                StoreOrder storeOrder = storeOrderService.getByOrderId(callbackVo.getOutTradeNo());
                if(Objects.isNull(storeOrder)){
                    throw new CrmebException("该订单不存在！"+callbackVo.getOutTradeNo());
                }
                if(!storeOrder.getUid().equals(attachVo.getUserId())){
                    throw new CrmebException("用户信息错误！");
                }
            }

//            //判断openid
//            UserToken userToken = userTokenService.getUserIdByOpenId(callbackVo.getOpenid());
//            if(null == userToken || !userToken.getUid().equals(attachVo.getUserId())){
//                //用户信息错误
//                throw new CrmebException("用户信息错误！");
//            }

            //根据类型判断是订单或者充值
            switch (attachVo.getType()){
                case Constants.SERVICE_PAY_TYPE_ORDER:
                    return orderPayService.success(callbackVo.getOutTradeNo(), attachVo.getUserId(), Constants.PAY_TYPE_WE_CHAT, callbackVo.getTransactionId(), request);
                case Constants.SERVICE_PAY_TYPE_RECHARGE:
                    return rechargePayService.success(callbackVo.getOutTradeNo(), attachVo.getUserId(), Constants.SERVICE_PAY_TYPE_MLRECHARGE, callbackVo.getTransactionId(), request);
                case Constants.SERVICE_PAY_TYPE_MEMBER:
                    return userMemberRecordService.successfulAfter(callbackVo.getOutTradeNo(), attachVo.getUserId(), callbackVo.getTransactionId());
                case Constants.SERVICE_PAY_TYPE_PRODUCT:
                    return channelMerchantPurchaseService.success(callbackVo.getOutTradeNo(), attachVo.getUserId(), callbackVo.getTransactionId());
                default:
                    throw new CrmebException("充值模块错误！");
            }

        }catch (Exception e){
            log.error("支付回调异常",e);
            return false;
        }
    }

    /**
     * 连连聚合支付回调
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public Boolean lianlianDegreePay(HttpServletRequest servletRequest) {
        // 从请求头中获取签名值
        String signature = servletRequest.getHeader("Signature-Data");
        BufferedReader reader = null;
        try{
            // 从请求体中获取源串
            reader = new BufferedReader(new InputStreamReader(servletRequest.getInputStream(), StandardCharsets.UTF_8));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            log.info("[接收来自连连下发的异步通知] 签名值为：" + signature);
            log.info("[接收来自连连下发的异步通知] 签名源串为：" + stringBuilder.toString());

            // 进行验签
            if (!notifyService.checkSign(stringBuilder.toString(), signature)) {
                // 验签失败，进行预警。
                log.error("--------------- 连连聚合支付验签失败, 原始参数: {}", stringBuilder.toString());

                return false;
            }
            // 下单结果
            LianlianPayResponse response = JSONObject.parseObject(stringBuilder.toString(), LianlianPayResponse.class);
            log.info("[接收来自连连下发的异步通知] response 为：" + JSONObject.toJSONString(response));
            /** 必传 */
            // 商户号，
            String oid_partner = response.getOid_partner();
            // 交易类型。
            String txn_type = response.getTxn_type();
            // 账务日期
            String accounting_date = response.getAccounting_date();
            // 支付完成时间
            String finish_time = response.getFinish_time();
            // ACCP系统交易单号
            String accp_txno = response.getAccp_txno();
            // 支付交易状态。
            String txn_status = response.getTxn_status();

            /** 可能返回     */
            // 渠道交易单号。
            String chnl_txno = response.getChnl_txno();
            // 银行编码
            String bankcode = response.getBankcode();
            // 	绑卡协议号
            String linked_agrtno = response.getLinked_agrtno();
            // 渠道流水号。如微信支付单号
            String pay_chnl_txno = response.getPay_chnl_txno();
            // 渠道商家订单号。如微信商家订单号。
            String sub_chnl_no = response.getSub_chnl_no();
            // 渠道扩展字段。json格式。需要特配异步通知返回格式。
            String channel_data = response.getChannel_data();

            /** 商户订单信息orderInfo */
            OrderInfoRequest orderInfo = response.getOrderInfo();
            log.info("[接收来自连连下发的异步通知] orderInfo 为：" + JSONObject.toJSONString(orderInfo));
            // 商户系统唯一交易流水号。由商户自定义。
            String txn_seqno = orderInfo.getTxn_seqno();
            String txn_time = orderInfo.getTxn_time();
            BigDecimal total_amount = orderInfo.getTotal_amount();
            String order_info = orderInfo.getOrder_info();



            /** 付款方信息（组合支付场景返回付款方信息数组）payerInfo */
            List<PayerInfoRequest> payerInfoRequestList = response.getPayerInfo();
            log.info("[接收来自连连下发的异步通知] payerInfoRequestList 为：" + JSONObject.toJSONString(payerInfoRequestList));
            if(CollectionUtils.isNotEmpty(payerInfoRequestList)) {
                for(PayerInfoRequest payerInfoRequest : payerInfoRequestList) {
                    String payer_type = payerInfoRequest.getPayer_type();
                    String payer_id = payerInfoRequest.getPayer_id();
                    String method = payerInfoRequest.getMethod();
                    String amount = payerInfoRequest.getAmount();
                    String acctno = payerInfoRequest.getAcctno();
                    String acctname = payerInfoRequest.getAcctname();
                    String chnl_payer_id = payerInfoRequest.getChnl_payer_id();
                }
            }

            /** 收款方信息（交易分账场景返回收款方信息数组）payeeInfo */
            List<PayeeInfoRequest> payeeInfoRequestList = response.getPayeeInfo();
            log.info("[接收来自连连下发的异步通知] payeeInfoRequestList 为：" + JSONObject.toJSONString(payeeInfoRequestList));
            if(CollectionUtils.isNotEmpty(payeeInfoRequestList)) {
                for(PayeeInfoRequest payeeInfoRequest : payeeInfoRequestList) {
                    String payee_type = payeeInfoRequest.getPayee_type();
                    String payee_id = payeeInfoRequest.getPayee_id();
                    String amount = payeeInfoRequest.getAmount();
                }
            }

            // 支付状态判断
            if(!"TRADE_SUCCESS".equals(txn_status)) {
                log.error("--------------- 连连聚合支付未成功支付, 原始参数: {}", JSON.toJSONString(response));
                return false;
            }
            if (txn_type.equals(Constants.MCH_TOPUP)) {
                ChannelMerchantPurchase order = channelMerchantPurchaseService.getOne(Wrappers.<ChannelMerchantPurchase>lambdaQuery().eq(ChannelMerchantPurchase::getOrderId, txn_seqno));
                // 支付金额判断
                if(null == order || 0 != order.getPrice().compareTo(total_amount)) {
                    log.error("--------------- 连连聚合支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(response));
                    return false;
                }
            } else if (txn_type.equals(Constants.USER_TOPUP)) {
                UserRecharge order = userRechargeService.getOne(Wrappers.<UserRecharge>lambdaQuery().eq(UserRecharge::getOrderId, txn_seqno));
                // 支付金额判断
                if(null == order || 0 != order.getPrice().compareTo(total_amount)) {
                    log.error("--------------- 连连聚合支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(response));
                    return false;
                }
            }else if (txn_type.equals(Constants.GENERAL_CONSUME)) {
                StoreOrder order = storeOrderService.getByOrderId(txn_seqno);
                // 支付金额判断
                if(null == order || 0 != order.getPayPrice().compareTo(total_amount)) {
                    log.error("--------------- 连连聚合支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(response));
                    return false;
                }
            }else if (txn_type.equals(Constants.SECURED_CONSUME)) {
                StoreOrder order = storeOrderService.getByOrderId(txn_seqno);
                // 支付金额判断
                if(null == order || 0 != order.getPayPrice().compareTo(total_amount)) {
                    log.error("--------------- 连连聚合支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(response));
                    return false;
                }
            }else{
                log.error("--------------- 连连聚合支付交易类型是什么: {}", txn_type);
                return false;
            }


            //根据类型判断支付功能
            switch (txn_type){
                case Constants.GENERAL_CONSUME:
                    // TODO pay_chnl_txno
                    Boolean result1 = orderPayService.success(txn_seqno, null, Constants.PAY_TYPE_LIANLIAN_DEGREE, pay_chnl_txno, JSON.toJSONString(response));
                    if(result1){
                        StoreOrder storeOrderPram1 = new StoreOrder();
                        storeOrderPram1.setOrderId(txn_seqno);
                        storeOrderPram1.setIsDel(false);
                        StoreOrder existStoreOrder1 = storeOrderService.getInfoByEntity(storeOrderPram1);
                        if(null != existStoreOrder1) {
                            merOrderService.toPushPayOrder(existStoreOrder1, null);
                        }
                    }
                    return result1;
                case Constants.SECURED_CONSUME:
                    // TODO pay_chnl_txno
                    Boolean result2 = orderPayService.success(txn_seqno, null, Constants.PAY_TYPE_LIANLIAN_DEGREE, pay_chnl_txno, JSON.toJSONString(response));
                    if(result2){
                        StoreOrder storeOrderPram2 = new StoreOrder();
                        storeOrderPram2.setOrderId(txn_seqno);
                        storeOrderPram2.setIsDel(false);
                        StoreOrder existStoreOrder2 = storeOrderService.getInfoByEntity(storeOrderPram2);
                        if(null != existStoreOrder2) {
                            merOrderService.toPushPayOrder(existStoreOrder2, null);
                        }
                    }
                    return result2;
                case Constants.USER_TOPUP:
                    // TODO pay_chnl_txno
                    return rechargePayService.success(txn_seqno, null, Constants.SERVICE_PAY_TYPE_LLRECHARGE, pay_chnl_txno, null);
                case Constants.MCH_TOPUP:
                    // TODO pay_chnl_txno
                    return channelMerchantPurchaseService.success(txn_seqno, null, pay_chnl_txno);
                default:
                    return false;
            }
        } catch (Exception e) {
            logger.error("连连聚合支付支付回调异常,", e);
            return false;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    logger.error("连连聚合支付支付回调reader关闭异常,", e);
                }
            }
        }

    }

    /**
     * 连连海关推单回调
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public Boolean lianlianDegreeCustoms(HttpServletRequest servletRequest) {
        // 从请求头中获取签名值
        String signature = servletRequest.getHeader("Signature-Data");
        BufferedReader reader = null;
        try{
            // 从请求体中获取源串
            reader = new BufferedReader(new InputStreamReader(servletRequest.getInputStream(), StandardCharsets.UTF_8));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            log.info("[接收来自连连海关推单回调下发的异步通知] 签名值为：" + signature);
            log.info("[接收来自连连海关推单回调下发的异步通知] 签名源串为：" + stringBuilder.toString());

            // 进行验签
            if (!notifyService.checkSign(stringBuilder.toString(), signature)) {
                // 验签失败，进行预警。
                log.error("--------------- 连连海关推单回调验签失败, 原始参数: {}", stringBuilder.toString());

                return false;
            }
            // 下单结果
            CustomsPushPayResponse response = JSONObject.parseObject(stringBuilder.toString(), CustomsPushPayResponse.class);
            log.info("[接收来自连连海关推单回调下发的异步通知] response 为：" + JSONObject.toJSONString(response));
            /** 必传 */
            String oid_partner = response.getOid_partner();
            String txn_seqno = response.getTxn_seqno();
            String accp_txno = response.getAccp_txno();
            String org_txn_seqno = response.getOrg_txn_seqno();
            String push_status = response.getPush_status();
            String pay_company_code = response.getPay_company_code();
            String pay_company_name = response.getPay_company_name();
            String pay_transaction_id = response.getPay_transaction_id();
            String push_failReason = response.getPush_failReason();

            // TODO 校验是否已经生成 StoreOrderCustoms 数据，没生成才能继续往下走
            int count = storeOrderCustomsService.count(Wrappers.<StoreOrderCustoms>lambdaQuery()
                    .eq(StoreOrderCustoms::getOrderNo, txn_seqno)
                    .eq(StoreOrderCustoms::getPayPushStatus, Boolean.TRUE)
            );
            if (0 < count) {
                log.error("该笔订单已报关完成 无需再次回调!");
                return true;
            }

            // 状态判断
            if ("PUSH_SUCCESSED".equals(push_status)) {
                StoreOrderCustoms storeOrderCustoms = new StoreOrderCustoms();
                storeOrderCustoms.setPayVerDept("3");
                storeOrderCustoms.setPayTransactionId(pay_transaction_id);
                // 子订单号
                storeOrderCustoms.setOrderNo(txn_seqno);
//                storeOrderCustoms.setInfoIds(infoIds.toString());
                storeOrderCustoms.setPayPushMsg(push_status);
                storeOrderCustoms.setPayPushStatus(Boolean.TRUE);
                storeOrderCustoms.setPayTransactionTime(new Date());
                storeOrderCustoms.setCreateTime(new Date());
                storeOrderCustomsService.save(storeOrderCustoms);
                return true;
            } else if ("PUSH_APPLY".equals(push_status)) {
                log.info("--------------- 连连聚合支付报关回调:推送申请（连连受理请求，暂未推送到海关的瞬时状态）!");
                return false;
            } else if ("PROCESSING".equals(push_status)) {
                log.info("--------------- 连连聚合支付报关回调:处理中");
                return false;
            } else {
                log.error("--------------- 连连聚合支付报关回调其他失败!: {}", push_failReason);
                StoreOrderCustoms storeOrderCustoms = new StoreOrderCustoms();
                storeOrderCustoms.setPayVerDept("3");
                storeOrderCustoms.setPayTransactionId(pay_transaction_id);
                // 子订单号
                storeOrderCustoms.setOrderNo(txn_seqno);
//                storeOrderCustoms.setInfoIds(infoIds.toString());
                storeOrderCustoms.setPayPushMsg(push_status);
                storeOrderCustoms.setPayPushStatus(Boolean.FALSE);
                storeOrderCustoms.setPayTransactionTime(new Date());
                storeOrderCustoms.setCreateTime(new Date());
                storeOrderCustomsService.save(storeOrderCustoms);
                return false;
            }

        } catch (Exception e) {
            logger.error("连连海关推回调异常,", e);
            return false;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    logger.error("连连海关推单回调reader关闭异常,", e);
                }
            }
        }
    }

    /**
     * 连连聚合支付退款回调
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public Boolean lianlianDegreeRefund(HttpServletRequest servletRequest) {

        // 验签
        // 从请求头中获取签名值
        String signature = servletRequest.getHeader("Signature-Data");
        BufferedReader reader = null;
        try {
            // 从请求体中获取源串
            reader = new BufferedReader(new InputStreamReader(servletRequest.getInputStream(), StandardCharsets.UTF_8));
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line);
            }
            log.info("[接收来自连连下发的退款异步通知] 签名值为：" + signature);
            log.info("[接收来自连连下发的退款异步通知] 签名源串为：" + stringBuilder.toString());

            // 进行验签
            if (!notifyService.checkSign(stringBuilder.toString(), signature)) {
                // 验签失败，进行预警。
                log.error("--------------- 连连聚合支付退款验签失败, 原始参数: {}", stringBuilder.toString());

                return false;
            }
        } catch (Exception e) {
            log.error("连连聚合支付退款失败,", e);
            return false;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    log.error("BufferedReader close 失败,", e);
                }
            }
        }
        return true;
    }

    /**
     * 汇付聚合支付回调
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public Boolean adapayDegreePay(Map<String, Object> parameter) {
    	try{
    		if(ObjectUtils.isEmpty(parameter)){
    			return false;
    		}
    		// 交易类型
    		String ext1 = parameter.get("ext1").toString();
    		// 退款(异步通知不处理)
    		if(Constants.SERVICE_PAY_TYPE_REFUND.equals(ext1)) {
    			return true;	
    		}
    		// 报关业务
    		if(Constants.SERVICE_PAY_TYPE_CUSTOMS.equals(ext1)) {
        		// 海关单独验签
//        		if(!checkAdapayDegreeSign(parameter)) {
//        			log.error("--------------- 汇付聚合支付验签失败, 原始参数: {}", JSON.toJSONString(parameter));
//        			return false;
//        		}
    			notifyCustoms(parameter);
    			
    			return true;
    		}
    		// 支付状态
    		String payResult = parameter.get("payResult").toString();
    		// 支付金额
    		String orderAmount = parameter.get("orderAmount").toString();
    		// 商户订单号
    		String orderId = parameter.get("orderId").toString();
    		// 第三方流水号
    		String dealId = parameter.get("dealId").toString();
    		// 支付状态判断
    		if(!"10".equals(payResult)) {
    			log.error("--------------- 汇付聚合支付未成功支付, 原始参数: {}", JSON.toJSONString(parameter));
    			return false;
    		}
            if (ext1.equals(Constants.SERVICE_PAY_TYPE_PRODUCT)) {
                ChannelMerchantPurchase order = channelMerchantPurchaseService.getOne(Wrappers.<ChannelMerchantPurchase>lambdaQuery().eq(ChannelMerchantPurchase::getOrderId, orderId));
                // 支付金额判断
                if(null == order || 0 != order.getPrice().movePointRight(2).compareTo(new BigDecimal(orderAmount))) {
                    log.error("--------------- 汇付聚合支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(parameter));
                    return false;
                }
            } else if (ext1.equals(Constants.SERVICE_PAY_TYPE_RECHARGE)) {
                UserRecharge order = userRechargeService.getOne(Wrappers.<UserRecharge>lambdaQuery().eq(UserRecharge::getOrderId, orderId));
                // 支付金额判断
                if(null == order || 0 != order.getPrice().movePointRight(2).compareTo(new BigDecimal(orderAmount))) {
                    log.error("--------------- 汇付聚合支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(parameter));
                    return false;
                }
            }else if (ext1.equals(Constants.SERVICE_PAY_TYPE_MEMBER)) {
                UserMemberRecord order = userMemberRecordService.getOne(Wrappers.<UserMemberRecord>lambdaQuery().eq(UserMemberRecord::getOrderNo, orderId));
                // 支付金额判断
                if(null == order || 0 != order.getPayPrice().movePointRight(2).compareTo(new BigDecimal(orderAmount))) {
                    log.error("--------------- 汇付聚合支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(parameter));
                    return false;
                }
            }
            else {
                StoreOrder order = storeOrderService.getByOrderId(orderId);
                // 支付金额判断
                if(null == order || 0 != order.getPayPrice().movePointRight(2).compareTo(new BigDecimal(orderAmount))) {
                    log.error("--------------- 汇付聚合支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(parameter));
                    return false;
                }
            }

    		// 验签
    		if(!checkAdapayDegreeSign(parameter)) {
    			log.error("--------------- 汇付聚合支付验签失败, 原始参数: {}", JSON.toJSONString(parameter));
    			return false;
    		}

            //根据类型判断支付功能
            switch (ext1){
                case Constants.SERVICE_PAY_TYPE_ORDER:
            		return orderPayService.success(orderId, null, Constants.PAY_TYPE_ADAPAY_DEGREE, dealId, JSON.toJSONString(parameter));
                case Constants.SERVICE_PAY_TYPE_RECHARGE:
                    return rechargePayService.success(orderId, null, Constants.SERVICE_PAY_TYPE_MLRECHARGE, dealId, null);
                case Constants.SERVICE_PAY_TYPE_MEMBER:
                    return userMemberRecordService.successfulAfter(orderId, null, dealId);
                case Constants.SERVICE_PAY_TYPE_PRODUCT:
                    return channelMerchantPurchaseService.success(orderId, null, dealId);
                default:
                    return false;
            }
    	} catch (Exception e) {
    		e.printStackTrace();
    		return false;
    	}
    	
    }
    
    /**
     * 汇付国内支付回调
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CrmebException.class})
    public Boolean adapayCnPay(Map<String, Object> parameter) {
    	try{
    		if(ObjectUtils.isEmpty(parameter)){
    			return false;
    		}
    		// 参数内容串
            String data = parameter.get("data").toString();
    		JSONObject dataJson = JSON.parseObject(data);
    		// 第三方流水
    		String dealId = dataJson.getString("id");
    		// 交易类型
    		String ext1 = dataJson.getString("description");
    		// 商户订单号
    		String orderId = dataJson.getString("order_no");
            // 签名串
            String sign = parameter.get("sign").toString();
    		// 支付状态
    		String payResult = dataJson.getString("status");
    		// 支付金额
    		String orderAmount = dataJson.getString("pay_amt");
    		// 退款(异步通知不处理)
    		if(Constants.SERVICE_PAY_TYPE_REFUND.equals(ext1)) {
    			return true;	
    		}
    		// 验签
    		if(!AdapaySign.verifySign(data, sign, AdapayCore.PUBLIC_KEY)) {
    			log.error("--------------- 汇付国内支付验签失败, 原始参数: {}", JSON.toJSONString(parameter));
    			return false;
    		}
    		// 支付状态判断
    		if(!"succeeded".equals(payResult)) {
    			log.error("--------------- 汇付国内支付未成功支付, 原始参数: {}", JSON.toJSONString(parameter));
    			return false;
    		}
    		StoreOrder order = storeOrderService.getByOrderId(orderId);
    		// 支付金额判断
    		if(null == order || 0 != order.getPayPrice().compareTo(new BigDecimal(orderAmount))) {
    			log.error("--------------- 汇付国内支付实际金额与订单金额不一致, 订单参数:{}  原始参数: {}", JSON.toJSONString(order), JSON.toJSONString(parameter));
    			return false;
    		}
    		
    		//根据类型判断支付功能
    		switch (ext1){
    		case Constants.SERVICE_PAY_TYPE_ORDER:
    			return orderPayService.success(orderId, null, Constants.PAY_TYPE_ADAPAY_DEGREE, dealId, null);
    		case Constants.SERVICE_PAY_TYPE_RECHARGE:
    			return rechargePayService.success(orderId, null, Constants.SERVICE_PAY_TYPE_MLRECHARGE, dealId, null);
    		case Constants.SERVICE_PAY_TYPE_MEMBER:
    			return userMemberRecordService.successfulAfter(orderId, null, dealId);
    		default:
    			return false;
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    		return false;
    	}
    	
    }

    /**
     * 支付宝支付回调
     * @author Mr.Zhang
     * @since 2020-05-06
     */
    @Override
    public Boolean aliPay(String request) {
        //根据类型判断是订单或者充值
        return false;
    }
    
    @Override
    public Boolean orangePay(Map<String, String[]> map) {
        boolean pay = false;
        if(ObjectUtils.isEmpty(map.get("userOrderNum"))){
            return pay;
        }
        String[] orderArr = (String[]) map.get("userOrderNum");
        // 验签
        if(!checkSign(map)) {
            log.info("橙子订单验签失败: {}", orderArr[0]);
            return pay;
        }
        // 判断是否后台充值
        UserRecharge userRecharge = userRechargeService.getOne(Wrappers.<UserRecharge>lambdaQuery()
                .eq(UserRecharge :: getOrderId, orderArr[0])
                .eq(UserRecharge :: getType, true)
                .last("LIMIT 1")
                );
        // 扫码支付
        if(null != userRecharge) {
            String[] codeArr = map.get("transactionStatusCode");
            log.info("橙子订单扫码支付状态: {}", codeArr[0]);
            return merRecharge(userRecharge, codeArr[0]);
        // 前端支付
        } else {
            StoreOrder order = storeOrderService.getByOrderId(orderArr[0]);
            String[] outOrderId = (String[]) map.get("orderNum");
            if(null!= order){
                order.setOutOrderId(outOrderId[0]);
                String[] codeArr = (String[]) map.get("transactionStatusCode");
                logger.info("橙子回调订单id:{} 订单 order :{} code ",codeArr[0],order ,codeArr[0]);
                if("2".equals(codeArr[0])){
                    if(Constants.ORDER_STATUS_H5_UNPAID == order.getStatus() || Constants.ORDER_STATUS_H5_CANCEL == order.getStatus()){
                        String[] amountArr = (String[]) map.get("amount");
                        logger.info("橙子回调订单金额,amount:{}",amountArr[0]);
                        BigDecimal amount = new BigDecimal(amountArr[0]);
                        pay = true;
                        if(order.getPayPrice().compareTo(amount) == 0){
                            orderPayService.afterPaySuccess(order);
                            return pay;
                        }else{
                            order.setMark("支付金额异常,请先检验一下订单");
                            orderPayService.afterPaySuccess(order);
                            return pay;
                        }
                    }else{
                        logger.info("订单不存在有异常 ======= 橙子回调订单id:{}",orderArr[0]);
                    }
                }
            }
        }
        
        return pay;
    }
    
    /**
     * 商户充值
     * @Description:  
     * @author daigb 
     * @param @param orderId
     * @return void
     * @throws
     */
    private Boolean merRecharge(UserRecharge userRecharge, String code) {
        if(userRecharge.getPaid()) {
            log.info("该订单已处理, 直接返回: {}", userRecharge.getOrderId());
            return true;
        }
        if(!"2".equals(code)){
        	log.info("订单未支付, 直接返回: {}", userRecharge.getOrderId());
        	return true;
        }
        // 资金操作
        ChannelMerchantAccount channelMerchantAccount = new ChannelMerchantAccount();
        channelMerchantAccount.setMerId(userRecharge.getMerId());
        channelMerchantAccount.setAccount(userRecharge.getPrice());
        channelMerchantAccountService.calcMoney(channelMerchantAccount);
        
        // 订单记录操作
        userRechargeService.update(Wrappers.<UserRecharge>lambdaUpdate()
                .eq(UserRecharge :: getId, userRecharge.getId())
                .set(UserRecharge :: getPaid, true)
                );
        
        // 流水操作
        accountFlowService.saveAccountFlow(userRecharge.getMerId(), userRecharge.getId(), userRecharge.getUid(), userRecharge.getIp(), AccountFlowTypeEnum.RECHARGE, userRecharge.getPrice(), null, null, "商户线上充值");

        return true;
    }

    @Override
    public Boolean rechargeNotify(Map map) {
        boolean pay = false;
        logger.info("橙子充值回调订单id:{}",map.get("userOrderNum"));
        if(ObjectUtils.isEmpty(map.get("userOrderNum"))){
            return pay;
        }
        String[] orderArr = (String[]) map.get("userOrderNum");
        UserRecharge userRecharge = new UserRecharge();
        userRecharge.setOrderId(orderArr[0]);
        UserRecharge recharge = userRechargeService.getInfoByEntity(userRecharge);
        logger.info("橙子充值回调订单id:{} 订单 order :{}",orderArr[0],recharge);
        String[] outOrderId = (String[]) map.get("orderNum");
        String[] codeArr = (String[]) map.get("transactionStatusCode");
        if(null!= recharge && "2".equals(codeArr[0])){
            if(!recharge.getPaid()){
                pay = rechargePayService.success(recharge.getOrderId(), recharge.getUid(), Constants.SERVICE_PAY_TYPE_ORRECHARGE,outOrderId[0], null);
                return pay;
            }else {
                logger.info("充值订单已经处理完成 orderid:{} 订单 order :{}",orderArr[0],recharge);
            }
        }
        return pay;
    }

    @Override
    public Boolean HKPay(String request) {
        try{
            log.info("----------------香港支付回调参数{}----------------",request);
            if(null == request){
                return false;
            }
            HashMap<String, Object> map = XmlUtil.xmlToMap(request);
            if(null == map){
                throw new CrmebException("香港支付下单失败！");
            }
            //验签
            if(!hkPayAttestation(map)){
                log.error("------------香港支付验签失败------------");
                return false;
            }
            log.info("----------------香港支付验签成功----------------");
            //解析xml
            HkPayCallbackVo hkCallbackVo = CrmebUtil.mapToObj(map, HkPayCallbackVo.class);
            HkPayAttachVo attachVo = JSONObject.toJavaObject(JSONObject.parseObject(hkCallbackVo.getAttach()), HkPayAttachVo.class);
            logger.info("香港支付回调成功,callbackVo对象:{}",hkCallbackVo);
            if (!"0".equals(hkCallbackVo.getStatus())){
                return false;
            }
            if (!"0".equals(hkCallbackVo.getResultCode())){
                return false;
            }
            //判断openid
            UserToken userToken = userTokenService.getUserIdByOpenId(hkCallbackVo.getSubOpenid());
            if(null == userToken || !userToken.getUid().equals(attachVo.getUserId())){
                //用户信息错误
                throw new CrmebException("用户信息错误！");
            }
            if (!"0".equals(hkCallbackVo.getPayResult())){
                return false;
            }
            StoreOrder order = storeOrderService.getByOrderId(hkCallbackVo.getOutTradeNo());
            if (order == null){
                logger.info("香港支付回调订单查询失败,order:{}",order);
                return false;
            }
            order.setOutOrderId(hkCallbackVo.getTransactionId());//平台订单号
            if(Constants.ORDER_STATUS_H5_UNPAID == order.getStatus() || Constants.ORDER_STATUS_H5_CANCEL == order.getStatus()){
                Integer totalFee = hkCallbackVo.getTotalFee();
                logger.info("香港支付回调订单金额,totalFee:{}",totalFee);
                BigDecimal amount = new BigDecimal(totalFee);
                if((order.getPayPrice().multiply(BigDecimal.TEN).multiply(BigDecimal.TEN)).compareTo(amount) == 0){
                    orderPayService.afterPaySuccess(order);
                    return true;
                }else{
                    order.setMark("支付金额异常,请先检验一下订单");
                    orderPayService.afterPaySuccess(order);
                    return true;
                }
            }else{
                logger.info("订单状态异常 ======= 香港支付回调订单id:{}",hkCallbackVo.getOutTradeNo());
                return false;
            }

        }catch (Exception e){
            logger.error("香港支付回调异常,Exception:{}",e);
            return false;
        }
    }

    /**
     * 香港支付验签
     * @param map
     * @throws Exception
     */
    public Boolean hkPayAttestation(HashMap<String, Object> map) throws Exception {
        //根据商户号获得merId
        SystemConfig systemConfig = systemConfigService.getOne(Wrappers.lambdaQuery(SystemConfig.class)
                .eq(SystemConfig::getName, WeChatConstants.HK_PAY_MCH_ID).eq(SystemConfig::getValue,map.get("mch_id")).last("LIMIT 1"));
        if(null == systemConfig){
            log.error("------------操作失败,香港支付商户号为空！------------");
            return false;
        }
        SystemConfig secretKeyConfig = systemConfigService.getOne(Wrappers.lambdaQuery(SystemConfig.class).eq(SystemConfig::getName, WeChatConstants.HK_PAY_SECRET_KEY)
                .eq(SystemConfig::getFormId, systemConfig.getFormId()).last("LIMIT 1"));
        if(null == secretKeyConfig){
            log.error("------------操作失败,香港支付密钥为空！------------");
            return false;
        }
        //验签
        String sign = WxPayUtil.generateSignature(map, secretKeyConfig.getValue(),map.get("sign_type").toString());
        if(!sign.equals(map.get("sign"))){
            log.error("------------香港支付签名验证失败！------------");
            return false;
        }
        return true;
    }

    @Override
    public Boolean rechargeNotifyHK(String request) {
        try{
            if(null == request){
                return false;
            }
            HashMap<String, Object> map = XmlUtil.xmlToMap(request);
            if(null == map){
                throw new CrmebException("香港支付充值失败！");
            }
            //验签
            if(!hkPayAttestation(map)){
                log.error("------------香港支付验签失败------------");
                return false;
            }
            //解析xml
            HkPayCallbackVo hkCallbackVo = CrmebUtil.mapToObj(map, HkPayCallbackVo.class);
            HkPayAttachVo attachVo = JSONObject.toJavaObject(JSONObject.parseObject(hkCallbackVo.getAttach()), HkPayAttachVo.class);
            logger.info("香港支付充值回调成功,callbackVo对象:{}",hkCallbackVo);
            if (!"0".equals(hkCallbackVo.getStatus())){
                return false;
            }
            if (!"0".equals(hkCallbackVo.getResultCode())){
                return false;
            }
            //判断openid
            UserToken userToken = userTokenService.getUserIdByOpenId(hkCallbackVo.getSubOpenid());
            if(null == userToken || !userToken.getUid().equals(attachVo.getUserId())){
                //用户信息错误
                throw new CrmebException("用户信息错误！");
            }
            if (!"0".equals(hkCallbackVo.getPayResult())){
                return false;
            }
            UserRecharge userRecharge = new UserRecharge();
            userRecharge.setOrderId(hkCallbackVo.getOutTradeNo());
            UserRecharge recharge = userRechargeService.getInfoByEntity(userRecharge);
            if (recharge == null){
                logger.info("香港支付回调充值查询失败,order:{}",recharge);
                return false;
            }
            if(!recharge.getPaid()){
                boolean result = rechargePayService.success(recharge.getOrderId(), recharge.getUid(), Constants.SERVICE_PAY_TYPE_HKRECHARGE, hkCallbackVo.getTransactionId(), request);
                return result;
            }else {
                logger.info("香港支付充值订单已经处理完成 orderid:{} 订单 order :{}",hkCallbackVo.getOutTradeNo(),recharge);
                return false;
            }
        }catch (Exception e){
            logger.error("香港支付回调异常,Exception:{}",e);
            return false;
        }
    }

    @Override
    public Boolean notifyMemberOrange(Map<String, String[]> map) {
        if(ObjectUtils.isEmpty(map.get("userOrderNum"))){
            return false;
        }
        String[] orderArr = (String[]) map.get("userOrderNum");
        // 验签
        if(!checkSign(map)) {
            log.info("橙子订单验签失败: {}", orderArr[0]);
            return false;
        }
        UserMemberRecord record = userMemberRecordService.getByOrderNo(orderArr[0]);
        String[] outOrderId = (String[]) map.get("orderNum");
        if(null!= record){
            String[] codeArr = (String[]) map.get("transactionStatusCode");
            logger.info("橙子回调订单id:{} ;code:{} ",codeArr[0] ,codeArr[0]);
            if("2".equals(codeArr[0])){
                if(record.getPaid() == 0){
                    String[] amountArr = (String[]) map.get("amount");
                    logger.info("橙子回调订单金额,amount:{}",amountArr[0]);
                    BigDecimal amount = new BigDecimal(amountArr[0]);
                    if(record.getPayPrice().compareTo(amount) == 0){
                        userMemberRecordService.successfulAfter(codeArr[0],null,outOrderId[0]);
                        return true;
                    }else{
                        logger.error("支付金额异常,请先检验一下订单{}",orderArr[0]);
                        return false;
                    }
                } else{
                    logger.info("订单不存在有异常 ======= 橙子回调订单id:{}",orderArr[0]);
                }
            }
        }
        return false;
    }

    @Override
    public Boolean notifyMemberHk(String request) {
        try{
            log.info("----------------香港支付回调参数{}----------------",request);
            if(null == request){
                return false;
            }
            HashMap<String, Object> map = XmlUtil.xmlToMap(request);
            if(null == map){
                throw new CrmebException("香港支付下单失败！");
            }
            //验签
            if(!hkPayAttestation(map)){
                log.error("------------香港支付验签失败------------");
                return false;
            }
            log.info("----------------香港支付验签成功----------------");
            //解析xml
            HkPayCallbackVo hkCallbackVo = CrmebUtil.mapToObj(map, HkPayCallbackVo.class);
            HkPayAttachVo attachVo = JSONObject.toJavaObject(JSONObject.parseObject(hkCallbackVo.getAttach()), HkPayAttachVo.class);
            logger.info("香港支付回调成功,callbackVo对象:{}",hkCallbackVo);
            if (!"0".equals(hkCallbackVo.getStatus())){
                return false;
            }
            if (!"0".equals(hkCallbackVo.getResultCode())){
                return false;
            }
            //判断openid
            UserToken userToken = userTokenService.getUserIdByOpenId(hkCallbackVo.getSubOpenid());
            if(null == userToken || !userToken.getUid().equals(attachVo.getUserId())){
                //用户信息错误
                throw new CrmebException("用户信息错误！");
            }
            if (!"0".equals(hkCallbackVo.getPayResult())){
                return false;
            }
            UserMemberRecord record = userMemberRecordService.getByOrderNo(hkCallbackVo.getOutTradeNo());
            if (record == null){
                logger.info("香港支付回调订单查询失败,order:{}",hkCallbackVo.getOutTradeNo());
                return false;
            }
            if(record.getPaid() == 0){
                Integer totalFee = hkCallbackVo.getTotalFee();
                logger.info("香港支付回调订单金额,totalFee:{}",totalFee);
                BigDecimal amount = new BigDecimal(totalFee);
                if((record.getPayPrice().multiply(BigDecimal.TEN).multiply(BigDecimal.TEN)).compareTo(amount) == 0){
                    userMemberRecordService.successfulAfter(hkCallbackVo.getOutTradeNo(),null,hkCallbackVo.getTransactionId());
                    return true;
                }else{
                    logger.error("支付金额异常,请先检验一下订单{}",hkCallbackVo.getOutTradeNo());
                    return false;
                }
            } else{
                logger.info("订单状态异常 ======= 香港支付回调订单id:{}",hkCallbackVo.getOutTradeNo());
                return false;
            }
        }catch (Exception e){
            logger.error("香港支付回调异常,Exception:{}",e.getMessage());
            return false;
        }
    }
    
    /**
     * 汇付聚合支付验签
     * @author daigb
     *
     * @date:  2022-07-19 14:21
     */
    private boolean checkAdapayDegreeSign(Map<String, Object> parameter) {
    	String dataReceived = "";
		List<String> keyList = new ArrayList<String>();
		Set<String> set = parameter.keySet();
		for(String key:set){
			if(SIGNATUREPARAMS.indexOf(key)>=0 && parameter.get(key)!= null && !StringUtils.isEmpty((String)parameter.get(key))){
				keyList.add(key);
			}
		}
		Collections.sort(keyList);
		for(String key:keyList){
			dataReceived = appendParam(dataReceived,key,(String)parameter.get(key));
		}
		String signMsg = (String) parameter.get("signMsg");
		boolean veryfyResult = false;
		try {
			//BG通知未转义，需要先转义
			veryfyResult = XMLSecurityProcess.veryfySignature(dataReceived, URLDecoder.decode(signMsg));
			//veryfyResult = XMLSecurityProcess.veryfySignature(dataReceived, signMsg);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
    	
    	return veryfyResult;
    }
	
	public String appendParam(String returns, String paramId, String paramValue) {
		if (returns != "") {
			if (paramValue != "") {

				returns += "&" + paramId + "=" + paramValue;
			}
		} else {

			if (paramValue != "") {
				returns = paramId + "=" + paramValue;
			}
		}
		return returns;
	}
	
	/**
	 * 报关业务处理
	 * @author daigb
	 * @date:  2022-08-18 15:48
	 */
	private void notifyCustoms(Map<String, Object> parameter) {
		String orderNo = parameter.get("orderId") + "";
		String decResult = parameter.get("decResult") + "";
		String errorMsg = parameter.get("errorMsg") + "";
		StoreOrderCustoms storeOrderCustoms = storeOrderCustomsService.getOne(Wrappers.<StoreOrderCustoms>lambdaQuery()
				.eq(StoreOrderCustoms :: getOrderNo, orderNo)
				.last("LIMIT 1")
				);
		if(null == storeOrderCustoms) {
			log.info("--------------- 汇付聚合支付未查到该笔报关订单数据: {}", orderNo);
			return;
		}
		if("20".equals(decResult)) {
			storeOrderCustoms.setPayPushStatus(true);
		} else {
			storeOrderCustoms.setPayPushStatus(false);
			storeOrderCustoms.setPayPushMsg(errorMsg);
		}
		storeOrderCustomsService.update(Wrappers.<StoreOrderCustoms>lambdaUpdate()
				.eq(StoreOrderCustoms :: getId, storeOrderCustoms.getId())
				.set(StoreOrderCustoms :: getPayPushStatus, storeOrderCustoms.getPayPushStatus())
				.set(StoreOrderCustoms :: getPayPushMsg, storeOrderCustoms.getPayPushMsg())
				);
	}

    private boolean checkSign(Map<String, String[]> map) {
        String sign = map.get("sign")[0];
        HashMap<String, Object> signMap = new HashMap<>();
        if(null != map.get("accountName")) {
            signMap.put("accountName", map.get("accountName")[0]);
        }
        if(null != map.get("amount")) {
            signMap.put("amount", map.get("amount")[0]);
        }
        if(null != map.get("orderNum")) {
            signMap.put("orderNum", map.get("orderNum")[0]);
        }
        if(null != map.get("createTime")) {
            signMap.put("createTime", map.get("createTime")[0]);
        }
        if(null != map.get("desc")) {
        	signMap.put("desc", map.get("desc")[0]);
        }
        if(null != map.get("payType")) {
            signMap.put("payType", map.get("payType")[0]);
        }
        if(null != map.get("payTypeName")) {
            signMap.put("payTypeName", map.get("payTypeName")[0]);
        }
        if(null != map.get("refundAmount")) {
            signMap.put("refundAmount", map.get("refundAmount")[0]);
        }
        if(null != map.get("serviceFee")) {
            signMap.put("serviceFee", map.get("serviceFee")[0]);
        }
        if(null != map.get("splitOrderList")) {
            signMap.put("splitOrderList", map.get("splitOrderList")[0]);
        }
        if(null != map.get("transactionStatus")) {
            signMap.put("transactionStatus", map.get("transactionStatus")[0]);
        }
        if(null != map.get("transactionStatusCode")) {
            signMap.put("transactionStatusCode", map.get("transactionStatusCode")[0]);
        }
        if(null != map.get("userOrderNum")) {
            signMap.put("userOrderNum", map.get("userOrderNum")[0]);
        }
        String checkSign = CrmebUtil.getOrangeSign(signMap, secret);
        
        return checkSign.equals(sign);
    }

}
